package com.ztgf.order.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.common.constant.CommonParameter;
import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.common.utils.DateUtils;
import com.ztgf.db.utils.RedisUtil;
import com.ztgf.dubbo.exception.ServiceException;
import com.ztgf.order.common.config.YmlConfig;
import com.ztgf.order.mapper.OrderStatusMapper;
import com.ztgf.order.models.bo.OrderExpirationDateSaveBO;
import com.ztgf.order.models.bo.OrderStatusSaveBO;
import com.ztgf.order.models.bo.OrderTimeRecordSaveBO;
import com.ztgf.order.models.bo.pay.PayOrderSaveBO;
import com.ztgf.order.models.constant.OrderExpireTimeConstant;
import com.ztgf.order.models.dto.*;
import com.ztgf.order.models.enums.OrderStateEnum;
import com.ztgf.order.models.service.*;
import com.ztgf.order.models.service.async.IAsyncOrderService;
import com.ztgf.order.models.service.pay.IPayService;
import com.ztgf.pay.models.service.IPayUserRechargeService;
import com.ztgf.shopping.models.dto.shop.ShopInfoDTO;
import com.ztgf.shopping.models.dto.shop.ShopSysInvoiceDTO;
import com.ztgf.shopping.models.service.shop.IShopInfoService;
import com.ztgf.sys.models.dto.SysDictDTO;
import com.ztgf.sys.models.service.ISysDictService;
import com.ztgf.user.models.dto.UserInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import static com.ztgf.common.utils.UtilConstants.TWO;

/**
 * 订单状态表控制器
 *
 * @author YUE
 * @Date 2020-06-23 10:33:48
 */
@Slf4j
@DubboService
@Lazy
public class OrderStatusServiceImpl extends ServiceImpl<OrderStatusMapper, OrderStatusDTO> implements IOrderStatusService {

    @Resource
    private YmlConfig ymlConfig;

    @Autowired
    @Lazy
    private IOrderInfoService orderInfoService;
    @Autowired
    @Lazy
    private IAsyncOrderService asyncOrderService;
    @Autowired
    private IOrderExpirationDateService orderExpirationDateService;

    @DubboReference
    private ISysDictService sysDictService;

    @Autowired
    private IOrderProcessLogService orderProcessLogService;

    @Autowired
    @Lazy
    private IOrderCommodityRelationService orderCommodityRelationService;

    @Autowired
    private IOrderTimeRecordService orderTimeRecordService;

    @Autowired
    private IOrderDeadlineRecordService orderDeadlineRecordService;

    @DubboReference
    private IPayUserRechargeService payUserRechargeService;

    @Autowired
    private IPayService payService;

    @Autowired
    private IOrderReturnCommodityService orderReturnCommodityService;

    @Autowired
    private RedisUtil redisUtil;

    @DubboReference
    private IShopInfoService shopInfoService;

    @Autowired
    private IOrderPaymentTypeService orderPaymentTypeService;

    @Autowired
    @Lazy
    private IOrderPayRelationService orderPayRelationService;

    @Override
    public Integer getUnfinishedOrderNum(Long ShopId, Integer type) {
        if (type == 1) {
            return baseMapper.getUnfinishedBuyerOrderNum(ShopId);
        }
        return baseMapper.getUnfinishedSellerOrderNum(ShopId);

    }

    @Override
    public Integer getUnfinishedInquiryOrderNum(Long shopId, Integer type) {
        if (type == 1) {
            return baseMapper.getUnfinishedBuyInquiryOrderNum(shopId);
        }
        return baseMapper.getUnfinishedSellerInquiryOrderNum(shopId);
    }

    @Override
    public boolean add(OrderStatusSaveBO saveBO) {
        OrderStatusDTO dto = new OrderStatusDTO();
        BeanUtils.copyProperties(saveBO, dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    /**
     * 获取所有签署中的订单
     *
     * @return
     */
    @Override
    public List<OrderStatusDTO> getListAuthingOrder(Long lastNo) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("contact_state", OrderStateEnum.ORDER_CONTACT_STATE_BUYER_SIGNING.getCode()).
                or().
                eq("contact_state", OrderStateEnum.ORDER_CONTACT_STATE_SELLER_SIGNING.getCode());
        wrapper.gt("order_id", lastNo);
        wrapper.orderBy("order_id", true);
        log.info("--------------lastNo="+lastNo);
        return baseMapper.selectPage(new Page<>(0, 50), wrapper);
    }

    /**
     * 获取所有废弃中的合同
     *
     * @return
     */
    @Override
    public List<OrderStatusDTO> getListSignAbandonOrder(Long lastNo) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("contact_state", 5);
        wrapper.gt("order_id", lastNo);
        wrapper.orderBy("order_id", true);
        return baseMapper.selectPage(new Page<>(0, 50), wrapper);
    }



    /**
     * 签署废弃合同
     *
     * @param orderId  订单id
     * @param signType 1买家签订 2卖家签订
     */
    @Override
    public void signAbandonContact(Long orderId, Integer signType) {
        OrderStatusDTO orderStatusDTO = getByOrderId(orderId);
        if (signType == 1) {
            orderStatusDTO.setBuyerContactAbandonState(2);
            if (orderStatusDTO.getSellerContactAbandonState() == 2) {//卖家已经签署废弃
                orderStatusDTO.setContactState(6);//合同状态变为废弃合同签署完成
            }
        } else {
            orderStatusDTO.setSellerContactAbandonState(2);
            if (orderStatusDTO.getBuyerContactAbandonState() == 2) {//买家已经签署废弃
                orderStatusDTO.setContactState(6);//合同状态变为废弃合同签署完成
            }
        }
        updateById(orderStatusDTO);
    }


    /*
     * @description:修改订单发票状态
     * @author: chenyu.wang
     * @date: 2020-08-17
     * @param:
     * @return:
     */
    @Override
    public void updateOrderInvoiceState(Long orderId) {
        log.info("订单发货修改订单发票状态,订单id : {}", orderId);
        Wrapper<OrderStatusDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        OrderStatusDTO dto = this.selectOne(wrapper);
        if (dto != null) {
            OrderStatusDTO updateDto = new OrderStatusDTO();
            updateDto.setId(dto.getId());
            updateDto.setInvoiceState(TWO);//已开票
            //添加订单日志表
            orderProcessLogService.addByOrderInfo(orderId, OrderStateEnum.ORDER_INVOICE_MADE.getCode());
            this.updateById(updateDto);
        }
    }

    /**
     * 添加信息
     *
     * @param orderId
     * @return
     */
    public boolean addByOrderInfo(Long orderId, Long invoiceHeadId) {
        OrderStatusDTO dto = new OrderStatusDTO();
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        dto.setOrderId(orderId);
        if (null != invoiceHeadId) {
            dto.setInvoiceState(1);//申请中;
        }
        return this.insert(dto);
    }

    /**
     * 更新维权状态
     *
     * @param orderId
     * @return
     */
    public boolean updateRightsProtection(Long orderId, int type, int status) {
        Wrapper<OrderStatusDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        OrderStatusDTO statusDTO = this.selectOne(wrapper);
        if (statusDTO == null) {
            return false;
        }
        OrderStatusDTO updateDTO = new OrderStatusDTO();
        updateDTO.setId(statusDTO.getId());
        if (type == 0) {
            updateDTO.setBuyersActivistState(status);

        } else {
            updateDTO.setSellerActivistState(status);
        }
        return updateById(updateDTO);
    }


    /**
     * 更新订单删除状态
     *
     * @param orderId
     * @return
     */
    @Override
    public boolean updateOrderDeleteState(Long orderId, int type) {
        OrderStatusDTO orderStatusDTO = getByOrderId(orderId);
        if (type == 0) {//买家删除
            orderStatusDTO.setBuyersDeleteState(1);
        } else {//卖家删除
            orderStatusDTO.setSellerDeleteState(1);
        }
        return updateById(orderStatusDTO);
    }

    @Override
    public void updateOrderShipWay(Long orderId) {
        log.info("订单发货修改订单状态,订单id : {}", orderId);
        Wrapper<OrderStatusDTO> wrapper = new EntityWrapper<>();
        wrapper.eq("order_id", orderId);
        OrderStatusDTO dto = this.selectOne(wrapper);
        if (null != dto) {
            OrderStatusDTO updateDto = new OrderStatusDTO();
            updateDto.setId(dto.getId());
            updateDto.setOrderState(4);//待签收
            boolean update = this.updateById(updateDto);
            if (update) {
                log.info("发货完成,订单状态修改成功!");
                //添加订单日志表
                orderProcessLogService.addByOrderInfo(orderId, OrderStateEnum.ORDER_WAIT_DELIVERY_GOODS.getCode());
            }
        } else {
            log.info("发货失败,未查询到订单状态");
        }
    }
//
//    @Override
//    public boolean updateReceived(Long orderId, Integer orderState) {
//        Wrapper<OrderStatusDTO> wrapper = new EntityWrapper<>();
//        wrapper.eq("order_id", orderId);
//        OrderStatusDTO dto = this.selectOne(wrapper);
//        if (dto == null) {
//            return false;
//        }
//        if (dto.getOrderState().equals(OrderStateEnum.ORDER_STATE_ENUM_SIGNED.getCode())) {
//            return false;
//        }
//        BigDecimal money = new BigDecimal("0");
//        //如果钱已经退完了，不走解冻和支付佣金
//        OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderId);
//        List<OrderCommodityRelationDTO> orderCommodityRelationDTOList = orderCommodityRelationService.getByOrderId(orderId);
//        for (OrderCommodityRelationDTO orderCommodityRelationDTO : orderCommodityRelationDTOList) {
//            money = money.add(orderCommodityRelationDTO.getReturnCommodityMoney());
//        }
//        //退款金额小于 实付金额 解冻 不然不执行
//        if (money.compareTo(orderInfoDTO.getActualMoney()) < 0) {
//            orderPayRelationService.thawOrderLastMoney(orderId);//解冻资金
//        }
//        OrderStatusDTO updateDto = new OrderStatusDTO();
//        updateDto.setId(dto.getId());
//        updateDto.setOrderState(orderState);
//        updateDto.setUpdateTime(new Date());
//        if (orderState == 6 || orderState == 7) {
//            updateDto.setContactState(5);
//            // 保存订单时间记录,已取消
//            OrderTimeRecordSaveBO timeRecordSaveBO = new OrderTimeRecordSaveBO();
//            timeRecordSaveBO.setOrderId(orderId);
//            timeRecordSaveBO.setOrderState(4);
//            orderTimeRecordService.add(timeRecordSaveBO);
//        }
//        updateDto.setIsExpiration(0);
//        //添加订单日志表
//        orderProcessLogService.addByOrderInfo(orderId, OrderStateEnum.ORDER_DEAL_SUCCESS.getCode());
//        return this.updateById(updateDto);
//    }

    /**
     * 订单签收
     * @param orderId
     * @param isCheckToken 是否效验token
     * @return
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public Result saveOrderReceive(Long orderId , boolean isCheckToken) {
        return saveOrderReceive(orderId, isCheckToken, true);
    }

    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public Result saveOrderReceive(Long orderId, boolean isCheckToken, boolean isFinish) {
        if(orderId == null){
            return new Result<>(CodeEnum.FAIL_100002);
        }
        OrderInfoDTO orderInfoDTO = orderInfoService.selectById(orderId);
        OrderStatusDTO orderStatusDTO = this.getByOrderId(orderId);
        if(orderInfoDTO == null || orderStatusDTO == null){
            return new Result<>(CodeEnum.FAIL_100002);
        }
        if(orderStatusDTO.getOrderState() != 4){
            return new Result<>(CodeEnum.ORDER_PAY_NOT_STATE);
        }

        Long userId = null;
        String userName = "";
        Long shopId = null;
        if(isCheckToken){
            Object object = redisUtil.getSession(CommonParameter.getHeadParamsBO().getSessionId (), CommonParameter.getHeadParamsBO().getSource().toString());
            if(object == null){
                return new Result(CodeEnum.FAIL_100002);
            }
            if(object instanceof UserInfoDTO){
                userId = ((UserInfoDTO) object).getId ();
                userName = ((UserInfoDTO) object).getName ();
            } else {
                return new Result(CodeEnum.FAIL_100002);
            }

            ShopInfoDTO shopInfoDTO = shopInfoService.getByUserId(userId);
            if(shopInfoDTO == null){
                return new Result(CodeEnum.FAIL_100053);
            }
            shopId = shopInfoDTO.getId();
        }
        saveReceive(orderInfoDTO, orderStatusDTO, isFinish);

        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
            log.error("---签收 解冻金额、支付佣金------>");
            PayOrderSaveBO payOrderSaveBO = new PayOrderSaveBO();
            payOrderSaveBO.setType(13);
            payOrderSaveBO.setIds(orderId.toString());
            payOrderSaveBO.setPayType(0);
            asyncOrderService.savePay(payOrderSaveBO, false);
        }
        });
        return new Result();
    }

    /**
     *
     * @param orderInfoDTO
     * @param orderStatusDTO
     * @param isFinsh true  必须判断完成
     */
    @Transactional(rollbackFor = ServiceException.class)
    public void saveReceive(OrderInfoDTO orderInfoDTO, OrderStatusDTO orderStatusDTO, boolean isFinsh){
        //根据订单id 获取商品列表
        BigDecimal allUnfreezeMoney = BigDecimal.ZERO;
        BigDecimal allCommissionMoney = BigDecimal.ZERO;
        BigDecimal allFeeMoney = BigDecimal.ZERO;

        BigDecimal lastOrderMoney = orderInfoDTO.getActualMoney();
        BigDecimal lastFeeMoney = orderInfoDTO.getPurchaseFeeMoneyScalePrice();

        //判断是否赊销订单存在未支付完成数据
        OrderPaymentTypeDTO orderPaymentTypeDTO = orderPaymentTypeService.getOrderPaymentByOrderIdAndType(orderInfoDTO.getId(), 1,2);
        List<OrderCommodityRelationDTO> commodityRelationDTOList = orderCommodityRelationService.getByOrderId(orderInfoDTO.getId());
        if(commodityRelationDTOList == null || commodityRelationDTOList.size() == 0){
            throw new ServiceException(CodeEnum.FAIL_100002);
        }
        //查询所有退款订单
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("order_id", orderInfoDTO.getId());
        List<OrderReturnCommodityDTO> returnCommodityDTOList = orderReturnCommodityService.selectList(wrapper);
        boolean isReturnOrder = true;
        boolean returnOrderFinsh = false;//判断是否全部退款

        if(returnCommodityDTOList != null && returnCommodityDTOList.size() > 0){
            for(OrderReturnCommodityDTO returnCommodityDTO : returnCommodityDTOList){
                if(returnCommodityDTO.getAfterSalesState() != 3){
                    isReturnOrder = false;
                    break;
                }
            }
            returnOrderFinsh = true;
        }

        if(!isReturnOrder){//是否有售后订单
            if(isFinsh){
                throw new ServiceException(CodeEnum.AFTER_SALE_ORDER_ERROR_320006);
            } else {
                return;
            }
        }
        //判断是否赊销订单存在未支付完成数据
        if(null != orderPaymentTypeDTO){//赊销存在未支付完成记录
            int orderState = 5;//签收状态
            int recordOrderState = 6;//签收状态时间
            int receiveStatus = 2; //签收
            int paySuccess = 1;
            for(OrderCommodityRelationDTO commodityRelationDTO : commodityRelationDTOList){
                lastOrderMoney = lastOrderMoney.subtract(commodityRelationDTO.getReturnCommodityMoney());
            }
            if(lastOrderMoney.compareTo(BigDecimal.ZERO) == 0 && returnOrderFinsh){//取消订单
                orderState = 6;
                recordOrderState = 4;
            } else {
                //判断是否支付完成
                boolean isPaySuccess = orderPayRelationService.getOrderAllPaySuccess(orderInfoDTO.getId(), null);
                if(isPaySuccess){ //支付完成
                    orderState = 5;
                    receiveStatus = 2;
                    paySuccess = 1;

                    // 订单取消删除订单倒计时
                    Wrapper<OrderExpirationDateDTO> a = new EntityWrapper<>();
                    a.eq("order_id", orderInfoDTO.getId());
                    orderExpirationDateService.delete(a);
                } else { //未支付完成
                    //直接修改订单状态为待支付
                    orderState = 2;
                    receiveStatus = 1;
                    paySuccess = 0;
                }
            }

            OrderStatusDTO newOrderStatusDTO = new OrderStatusDTO();
            newOrderStatusDTO.setId(orderStatusDTO.getId());
            newOrderStatusDTO.setOrderState(orderState);
            if(lastOrderMoney.compareTo(BigDecimal.ZERO) > 0){
                newOrderStatusDTO.setLastMoney(lastOrderMoney);
            }

            OrderPaymentTypeDTO newOrderPaymentTypeDTO = new OrderPaymentTypeDTO();
            newOrderPaymentTypeDTO.setId(orderPaymentTypeDTO.getId());
            newOrderPaymentTypeDTO.setReceiveStatus(receiveStatus);//签收中
            newOrderPaymentTypeDTO.setPaymentStatus(paySuccess);
            this.updateById(newOrderStatusDTO);
            orderPaymentTypeService.updateById(newOrderPaymentTypeDTO);

            OrderTimeRecordSaveBO timeRecordSaveBO = new OrderTimeRecordSaveBO();
            timeRecordSaveBO.setOrderId(orderInfoDTO.getId());
            timeRecordSaveBO.setOrderState(recordOrderState);//写入签收时间
            boolean flag = orderTimeRecordService.insert(timeRecordSaveBO);
            if(!flag){
                throw new ServiceException(CodeEnum.FAIL_ORDER_300010);
            }
            return;
        }

        if(orderInfoDTO.getSellPayType() == 0){//担保
            for(OrderCommodityRelationDTO commodityRelationDTO : commodityRelationDTOList){
                //计算可解冻金额，可解冻服务费
                BigDecimal unfreezeMoney = commodityRelationDTO.getActualMoney().subtract(commodityRelationDTO.getReturnCommodityMoney());
                allUnfreezeMoney = allUnfreezeMoney.add(unfreezeMoney);
                //佣金
                BigDecimal commissionMoney = BigDecimal.ZERO;
                if(unfreezeMoney.compareTo(BigDecimal.ZERO) > 0){
                    commissionMoney = unfreezeMoney.multiply(commodityRelationDTO.getCommissionRate()).setScale(2, BigDecimal.ROUND_UP);//向上舍入
                }
                allCommissionMoney = allCommissionMoney.add(commissionMoney);
                //砍价手续费
                BigDecimal feeMoney = BigDecimal.ZERO;
                if(commodityRelationDTO.getPurchaseFeeMoneyScalePrice().compareTo(BigDecimal.ZERO) > 0){
                    feeMoney = commodityRelationDTO.getPurchaseFeeMoneyScalePrice().subtract(commodityRelationDTO.getPurchaseFeeMoneyScaleBackPrice());
                }
                allFeeMoney = allFeeMoney.add(feeMoney);

                //最后的订单金额
                lastOrderMoney = lastOrderMoney.subtract(commodityRelationDTO.getReturnCommodityMoney());
                //解冻砍价手续费金额
                lastFeeMoney = lastFeeMoney.subtract(commodityRelationDTO.getPurchaseFeeMoneyScaleBackPrice());
            }

//            if(orderInfoDTO.getPayType() == 1){//分批 减去已解冻金额
//                OrderPayRelationDTO oldOrderPayRelationDTO = orderPayRelationService.getByOrderIdAndPeriods(orderInfoDTO.getId(), 1);//一期
//                if(!(oldOrderPayRelationDTO.getPayType() != null && oldOrderPayRelationDTO.getPayType() == 2 && oldOrderPayRelationDTO.getPayState() == 2)){//票据支付 或者赊销订单 不解冻
//                    allUnfreezeMoney = allUnfreezeMoney.subtract(oldOrderPayRelationDTO.getRealPayMoney());
//                    if(allUnfreezeMoney.compareTo(BigDecimal.ZERO) < 0){
//                        allUnfreezeMoney = BigDecimal.ZERO;
//                    }
//                }
//
//            }

            List<OrderPayRelationDTO> relationDTOList = orderPayRelationService.getByOrderId(orderInfoDTO.getId());
            if(relationDTOList != null && relationDTOList.size() > 0){

                for(OrderPayRelationDTO relationDTO : relationDTOList){
                    if(orderInfoDTO.getPayType() == 0){//全款
                        if(relationDTO.getPayType() != null && relationDTO.getPayType() == 2 && relationDTO.getPayState() == 2){
                            allUnfreezeMoney = allUnfreezeMoney.subtract(relationDTO.getRealPayMoney());
                        }
                    } else {//分期
                        if(relationDTO.getPeriods() == 1){
                            allUnfreezeMoney = allUnfreezeMoney.subtract(relationDTO.getRealPayMoney());
                        } else {
                            if(relationDTO.getPayType() != null && relationDTO.getPayType() == 2 && relationDTO.getPayState() == 2){
                                allUnfreezeMoney = allUnfreezeMoney.subtract(relationDTO.getRealPayMoney());
                            }
                        }
                    }
                }
                if(allUnfreezeMoney.compareTo(BigDecimal.ZERO) < 0){
                    allUnfreezeMoney = BigDecimal.ZERO;
                }
            }
        }
        Integer orderState = 5;
        Integer recordOrderState = 6;

        //修改订单表信息
        OrderInfoDTO newOrderInfoDTO = new OrderInfoDTO();
        //修改订单状态表信息
        OrderStatusDTO newOrderStatusDTO = new OrderStatusDTO();

        if(lastOrderMoney.compareTo(BigDecimal.ZERO) == 0 && returnOrderFinsh){//取消订单
            orderState = 6;
            recordOrderState = 4;
        }

        if(allUnfreezeMoney.compareTo(BigDecimal.ZERO) > 0){
            newOrderStatusDTO.setUnfreezeMoney(allUnfreezeMoney);
        }

        if(allFeeMoney.compareTo(BigDecimal.ZERO) > 0){
            newOrderStatusDTO.setUnfreezePurchaseFeeMoneyScalePrice(allFeeMoney);
        }

        if(lastOrderMoney.compareTo(BigDecimal.ZERO) > 0){
            newOrderStatusDTO.setLastMoney(lastOrderMoney);
        }

        if(lastFeeMoney.compareTo(BigDecimal.ZERO) > 0){
            newOrderStatusDTO.setLastPurchaseFeeMoneyScalePrice(lastFeeMoney);
        }
        newOrderStatusDTO.setOrderState(orderState);
        if(allCommissionMoney.compareTo(BigDecimal.ZERO) > 0){
            log.error("---最后佣金allCommissionMoney--->" + allCommissionMoney);
            newOrderInfoDTO.setLastCommissionMoney(allCommissionMoney);
            //修改订单信息
            wrapper = new EntityWrapper();
            wrapper.eq("id", orderInfoDTO.getId());
            wrapper.eq("last_commission_money", orderInfoDTO.getLastCommissionMoney());
            boolean flag = orderInfoService.update(newOrderInfoDTO, wrapper);
            if(!flag){
                throw new ServiceException(CodeEnum.FAIL_ORDER_300010);
            }
        }
        //修改订单信息
        wrapper = new EntityWrapper();
        wrapper.eq("order_id", orderInfoDTO.getId());
        wrapper.eq("order_state", orderStatusDTO.getOrderState());
        boolean flag = this.update(newOrderStatusDTO, wrapper);
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_ORDER_300010);
        }

        OrderTimeRecordSaveBO timeRecordSaveBO = new OrderTimeRecordSaveBO();
        timeRecordSaveBO.setOrderId(orderInfoDTO.getId());
        timeRecordSaveBO.setOrderState(recordOrderState);
        flag = orderTimeRecordService.insert(timeRecordSaveBO);//普通订单（非赊销）
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_ORDER_300010);
        }
        // 订单取消删除订单倒计时
        Wrapper<OrderExpirationDateDTO> a = new EntityWrapper<>();
        a.eq("order_id", orderInfoDTO.getId());
        flag = orderExpirationDateService.delete(a);
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_ORDER_300010);
        }
        //添加订单日志表
        flag = orderProcessLogService.addByOrderInfo(orderInfoDTO.getId(), OrderStateEnum.ORDER_DEAL_SUCCESS.getCode());
        if(!flag){
            throw new ServiceException(CodeEnum.FAIL_ORDER_300010);
        }

    }


    /**
     * 更新订单状态为 生产完成
     *
     * @param orderId
     * @return
     */
    @Transactional
    @Override
    public boolean updateOrderStateByProductionState(Long orderId) {
        OrderStatusDTO orderStatusDTO = getByOrderId(orderId);
        orderStatusDTO.setGoodsProductionState(OrderStateEnum.ORDER_GOODS_PRO_OVER.getCode());
        //更新倒计时
        OrderExpirationDateDTO orderExpirationDateDTO = orderExpirationDateService.getByOrderId(orderId);
        SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.SELLER_SIGN_TIME);//卖家签订合同后倒计时
        String time = sysDictDTO.getValue();
        Date currentDateTime = DateUtils.getCurrentDateTime();//当前时间
        Date expireTime = DateUtils.addDay(currentDateTime, Integer.parseInt(time));//过期时间
        orderExpirationDateDTO.setExpirationTime(expireTime);
        orderExpirationDateDTO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_PAY.getCode());
        orderExpirationDateService.updateByOrderId(orderExpirationDateDTO);//更新过期时间
        // 记录二期待付款截止时间
        orderDeadlineRecordService.add(orderId, 7, expireTime);
        // 记录生产完成时间
        orderDeadlineRecordService.add(orderId, 8, currentDateTime);
        return updateById(orderStatusDTO);
    }

    /**
     * 获取订单状态信息
     *
     * @param orderId 订单id
     * @return
     */
    @Override
    public OrderStatusDTO getByOrderId(Long orderId) {
        OrderStatusDTO orderStatusDTO = new OrderStatusDTO();
        orderStatusDTO.setOrderId(orderId);
        return baseMapper.selectOne(orderStatusDTO);
    }

    /**
     * 更新订单状态为 签署
     *
     * @param orderId
     * @param type    1 买家签订 2卖家签订
     * @return
     */
    @Transactional
    public Result<?> contactSign(Long orderId, int type) {
        OrderStatusDTO orderStatusDTO = getByOrderId(orderId);
        String time = "0";
        //boolean isDown = true;
        Date currentDateTime = DateUtils.getCurrentDateTime();//当前时间
        SimpleDateFormat sformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//日期格式
        if (type == 1) {//买家签订
            //orderStatusDTO.setGoodsProductionState(OrderStateEnum.ORDER_GOODS_PRO_ING.getCode());//生产状态生产中
            SysDictDTO sysDictDTO = sysDictService.getByName(OrderExpireTimeConstant.BUYER_SIGN_TIME);//买家签订倒计时
            time = sysDictDTO.getValue();
            Date expireTime = DateUtils.addDay(currentDateTime, Integer.parseInt(time));//过期时间
            //增加过期时间
            OrderExpirationDateSaveBO orderExpirationDateSaveBO = new OrderExpirationDateSaveBO();
            orderExpirationDateSaveBO.setOrderId(orderId);
            orderExpirationDateSaveBO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_CONTACT.getCode());
            orderExpirationDateSaveBO.setExpirationTime(expireTime);
            //添加过期时间
            orderExpirationDateService.add(orderExpirationDateSaveBO);
            // 保存订单记录时间
            OrderTimeRecordSaveBO saveBO = new OrderTimeRecordSaveBO();
            saveBO.setOrderId(orderId);
            saveBO.setOrderState(2);
            orderTimeRecordService.add(saveBO);
            // 待卖家签订截止时间记录
            orderDeadlineRecordService.add(orderId, 3, expireTime);
            String tiem = sformat.format(orderExpirationDateSaveBO.getExpirationTime());
            log.info("orderid-------"+orderId+"--------过期时间0----------"+tiem);

            orderStatusDTO.setContactState(type);
            boolean b = updateById(orderStatusDTO);
            if (!b) {
                log.error("签署失败");
                throw new RuntimeException("签署失败");
            }
        } else if (type == 2) {//卖家签订
            log.info("卖家签订合同开始----------start----------orderId="+orderId);
            //买家未签订卖家不能签订
            if (orderStatusDTO.getContactState() == OrderStateEnum.ORDER_CONTACT_STATE_NO_SIGN.getCode()) {
                return new Result<>(CodeEnum.FAIL_ORDER_BUYER_NO_SIGN_CONTACT_310004);
            }

//            //判断是否赊销订单
//            OrderPaymentTypeDTO orderPaymentTypeDTO = orderPaymentTypeService.getOrderPaymentByOrderIdAndType(orderId,1,2);
//            if(null != orderPaymentTypeDTO){
//                //获取订单商品关联关系
//                List<OrderCommodityRelationDTO> orderCommodityRelationDTOList = orderCommodityRelationService.getByOrderId(orderId);
//                List<Integer> sendList = new ArrayList<Integer>();
//                //处理多个商品中获取发货时间为最少的
//                for(OrderCommodityRelationDTO orderCommodityRelationDTO : orderCommodityRelationDTOList){
//                    sendList.add(orderCommodityRelationDTO.getSendDays());
//                }
//                Integer sendDaysNum = Collections.min(sendList);
//                Date expireTime = DateUtils.addDay(currentDateTime, sendDaysNum);//过期时间
//
//                //卖家签订完合更新发货截至时间（赊销）
//                // 待发货截止时间
//                orderDeadlineRecordService.add(orderId, 5, expireTime);
//                //更新倒计时
//                OrderExpirationDateDTO orderExpirationDateDTO = orderExpirationDateService.getByOrderId(orderId);
//                orderExpirationDateDTO.setExpirationTime(expireTime);
//                orderExpirationDateDTO.setStatus(OrderStateEnum.ORDER_STATE_ENUM_WAIT_PAY.getCode());
//                orderExpirationDateService.updateByOrderId(orderExpirationDateDTO);//更新倒计时
//                log.info("赊销--待发货时间:"+expireTime);
//            }
            log.info("卖家签订orderId="+orderId);
            return payService.saveSellContactSuccess(orderId);
        }



        return new Result<>();
    }

    /**
     * 同步技术服务费（买家申请平台砍价成功）
     * @return
     */
    @Override
    public List<ShopSysInvoiceDTO> getSynchronizationShopSysInvoiceBuy() {
        return baseMapper.getSynchronizationShopSysInvoiceBuy();
    }

}
